package com.joymart.product.repo;


import com.joymart.common.data.jdbc.BaseRepository;
import com.joymart.product.model.Stock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;


@Repository
public class StockRepository{

    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * select for update，记得update和开启transactional注解
     * @param productId
     * @return
     */
    public Integer selectForUpdate(String productId){
        String sql = "select quantity from stock where product_id=? for update";
        return jdbcTemplate.queryForObject(sql, Integer.class, productId);
    }

    public void updateQuantity(String productId, int quantity){
        String sql = "update stock set quantity=? where product_id=?";
        jdbcTemplate.update(sql, quantity, productId);
    }

    public Integer getCurrentStock(String productId) {
        String sql = "select quantity from stock where product_id=?";
        return jdbcTemplate.queryForObject(sql, Integer.class, productId);
    }
}
